<template>
  <div id="app" class="spare-part-apply-for" ref="sparePartApplyForRef" tabindex="0">
    <!-- 头部导航 -->
    <van-nav-bar left-arrow title="备件采购申请" @click-left="comeBack" left-text="返回">
<!--      <template #right>
        <span @click="showInPopupFn"><van-icon name="scan" size="20" /></span>
      </template>-->
    </van-nav-bar>

    <!-- 筛选 -->
    <van-search v-model="queryParam.keyLike" placeholder="请输入搜索关键词" @search="() => loadSparePartApplyForDataFn(1)" />

    <!-- 滚动 -->
    <better-scroll class="body-scroll" :data="sparePartApplyForData" :total-page="totalPage" :pulldown="true" :pullup="true" @pullup="loadNextPageFn" @pulldown="() => loadSparePartApplyForDataFn(1)">
      <van-swipe-cell v-show="sparePartApplyForData.length > 0" v-for="(row, rIndex) in sparePartApplyForData" :key="row.id" style="padding-bottom: 0.5rem">
        <template>
          <div :class="renderClassFn(row)" class="data-card">
            <div style="flex: 0 0 18vw">
              <van-image width="15vw" height="12vh" fit="fill" :src="row.picView" @click="showPicPreViewFn(row)">
                <template v-slot:error>加载失败</template>
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>
            </div>
            <div style="flex: 1; flex-flow: column;">
              <div style="border-bottom: 1px solid #8191c5;" >
                <span style="color: #8191c5;font-size: 1.2rem; ">{{ row.name }}</span>
              </div>
              <div>
                <span style="color: #bb5a09;font-size: 1.1rem; ">{{ row.standard == SPLIT_BLANK ? "无规格" : row.standard }}</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #e6a23c">申请数量: {{ row.num }}</span>
                <span style="color: #e6a23c">申请人: {{ row.optName }}</span>
              </div>
              <div>
                <span style="color: #232323;font-size: 1rem; ">{{ row.createAt }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square size="small" type="danger" @click="cancelApplyForFn(row)">取消</van-button>
            <van-button square style="margin-top: 1vh;" size="small" type="info" @click="showCheckDialogFn(row)">审批</van-button>
            <van-button square style="margin-top: 1vh;" size="small" type="primary" @click="showInPopupFn(row)">扫码入库</van-button>
          </div>
        </template>
      </van-swipe-cell>
      <van-empty  v-show="sparePartApplyForData.length == 0" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无数据" ></van-empty>
    </better-scroll>

    <!-- 图片预览 -->
    <van-image-preview v-model="showPicPreViewFlag" :showIndex="false" :closeable="true" :images="picPreView">
    </van-image-preview>

    <!-- 审核窗口 -->
    <van-dialog v-model="check.show" title="请选择审批操作" :lock-scroll="false" :show-cancel-button="true" :show-confirm-button="true" @confirm="checkApplyForSparePart">
      <template #default>
        <div style="padding-left:5vw;padding-top: 3vh;">
          <van-radio-group direction="horizontal" v-model="check.opt">
            <van-radio name="2" shape="square">去采购</van-radio>
            <van-radio name="5" shape="square">驳回</van-radio>
          </van-radio-group>
          <van-field style="padding-top: 2vh" label-width="18vw" label="审批备注" type="textarea" colon clearable placeholder="请说明" v-model="check.remark"></van-field>
        </div>
      </template>
    </van-dialog>

    <!-- 扫码入库弹窗 -->
    <van-popup style="width: 70vw;padding: 1vh 2vw;max-height: 50vh;overflow: auto;" v-model="scanIn.show" get-container="#app">
      <van-swipe-cell v-if="scanIn.data.length > 0" v-for="(inData, index) in scanIn.data" :key="inData.id" style="padding-bottom: 0.5rem">
        <template>
          <div v-if="scanIn.data.length > 0" style="display: flex;justify-content: center;flex-flow: column;box-shadow: 0.3rem 0.5rem 0.3rem #888888;margin-top: 0.5rem;">
            <div style="border-bottom: 1px solid #8191c5;" ><span>名称:{{ inData.name }}</span></div>
            <div style="color: #bb5a09;font-size: 1.1rem;"><span>规格:{{ inData.standard }}</span></div>
<!--            <van-field label="区域" colon clearable placeholder="请输入或选择区域" v-model="inData.area">
              <template #button>
                <van-button type="info" native-type="button" size="small" @click="filterDataFn(inData, 100)">筛选</van-button>
              </template>
            </van-field>-->
            <div>
              <van-field type="digit" v-model="inData.num" label="数量"></van-field>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square style="margin-top: 1vh;" size="small" type="danger" @click="delDetailFn(inData, index)">删除</van-button>
          </div>
        </template>
      </van-swipe-cell>
      <div v-if="scanIn.data.length == 0">
        <span>采购完入库请扫码...</span>
      </div>
      <div style="display: flex;justify-content: center;margin-top: 2vh;">
        <van-button size="small" block type="danger" native-type="button" @click="scanIn.show = false">取消</van-button>
        <van-button size="small" style="margin-left: 5vw;" block type="info" @click="openScanWinFn">扫码</van-button>
        <van-button size="small" style="margin-left: 5vw;" block type="primary" @click="confirmScanInFn">确定</van-button>
      </div>
    </van-popup>

    <!-- 弹出面板 -->
    <van-action-sheet v-model="showActionSheet" :actions="actionSheetData" title="请选择" cancel-text="取消" close-on-click-action get-container="#app" @cancel="showActionSheet = false" @select="selectFilterDataFn"></van-action-sheet>
  </div>
</template>

<script>
import {comeBack, openWin} from "@/utils";
import {
  SPARE_PART_RECYCLING_ENUM,
  SPARE_PART_ROOM_ENUM,
  SPARE_PART_TYPE_ENUM, sparePartRecyclingEnumFn, sparePartRoomEnumFn,
  sparePartTypeEnumFn,
  SPLIT_BLANK,
  SPLIT_COMMA,
  SPLIT_YKH,
  SPLIT_ZKH, UNIT_ENUM, unitEnumFn
} from "@/api/enum";
import {getUploadKey} from "@/api/public";
import {exportBaseUrl} from "@/utils/request";
import {
  cancelApplyForSparePart,
  checkApplyForSparePart, filterSpareArea, filterSpareDevice, filterSpareSupplier,
  loadSparePartApplyForData, loadSparePartData, procureIn, sparePartDetail,
  sparePartDetailDetail
} from "@/views/spare-part/spare-part.js";

export default {
  name: "sparePartApplyFor",
  data() {
    return {
      SPLIT_ZKH, SPLIT_YKH, SPLIT_BLANK,

      /* 查询相关 */
      queryParam: {
        keyLike: "",
        pageNum: 1,
        pageSize: 10,
      },
      queryTimer: null,

      /* 列表相关 */
      sparePartApplyForData: [],
      totalPage: 0,

      /* 图片相关 */
      picType: "WLBJ",
      showPicPreViewFlag: false,
      picPreView: [],

      curRow: null,
      /* 审核相关 */
      check: {
        show: false,
        opt: "2",
        remark: "",
      },

      /* 入库 */
      scanIn: {
        curData: null,
        show: false,
        data: []
      },

      /* 数据面板 */
      showActionSheet: false,
      actionSheetData: [],
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    comeBack,

    /* 初始化 */
    initFn() {
      const that = this;

      //加载数据
      that.loadSparePartApplyForDataFn(1);
    },

    /* 加载备件申请单 */
    loadSparePartApplyForDataFn(pageNum) {
      const that = this;
      if(pageNum == 1) {
        that.queryParam.pageNum = 1;
        that.sparePartApplyForData.splice(0, that.sparePartApplyForData.length);
      }
      loadSparePartApplyForData(that.queryParam, data => {
        if(!data.code && data.code != 0) {
          that.totalPage = data.totalPage;
          data.list.forEach(row => {
            that.fillPicViewFn(that, row);
            that.sparePartApplyForData.push(row);
          });
        }
      });
    },
    fillPicViewFn(that, row) {
      row.picView = "";
      getUploadKey({
        type: that.picType
      }, tokenRes => {
        row.picView = exportBaseUrl("res") + "/res_thumb/" + row.pic.split(SPLIT_COMMA)[0] + '?accessToken=' + tokenRes.accessToken;
      });
    },

    /* 加载下一页 */
    loadNextPageFn() {
      let that = this;
      that.queryParam.pageNum++;
      that.loadSparePartApplyForDataFn();
    },

    /* 显示预览图 */
    showPicPreViewFn(row) {
      const that = this;
      that.picPreView.splice(0, that.picPreView.length);
      row.pic.split(SPLIT_COMMA).forEach(pic => {
        getUploadKey({
          type: that.picType
        }, tokenRes => {
          that.picPreView.push(exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken);
        });
      });
      that.showPicPreViewFlag = true;
    },

    /* 渲染 */
    renderClassFn(row) {
      if(row.status == 1) {
        return "status-to-check";
      } else if(row.status == 2) {
        return "status-to-procure";
      } else if(row.status == 3) {
        return "status-in";
      } else if(row.status == 5) {
        return "status-reject";
      } else {
        return "";
      }
    },

    /* 取消申请 */
    cancelApplyForFn(row) {
      const that = this;
      that.$dialog.confirm({
        title: "请确认",
        message: "确定取消申请吗?",
      }).then(() => {
        cancelApplyForSparePart({
          applyForId: row.id
        }, () => {
          that.$toast.success({
            message: "取消成功",
            onClose: () => {
              that.loadSparePartApplyForDataFn(1);
            }
          });
        });
      }).catch(() => {
      });
    },

    /* 显示审核弹窗 */
    showCheckDialogFn(row) {
      const that = this;
      that.curRow = row;
      that.check.show = true;
    },

    /* 审核申请 */
    checkApplyForSparePart() {
      const that = this;
      checkApplyForSparePart({
        applyForId: that.curRow.id,
        status: that.check.opt,
        checkRemark: that.check.remark,
      }, () => {
        that.$toast.success({
          message: "审核成功",
          onClose: () => {
            that.loadSparePartApplyForDataFn(1);
          }
        });
      });
    },

    /* 显示入库弹窗 */
    showInPopupFn(row) {
      const that = this;
      that.scanIn.data.splice(0, that.scanIn.data.length);
      that.curRow = row;
      that.scanIn.show = true;
    },

    /* 打开扫码窗 */
    openScanWinFn() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          if(ret.result.indexOf("33,") == 0) {    //采购码
            let ids = ret.result.split(SPLIT_COMMA);
            if(ids.length != 2) {
              that.$toast.fail("二维码异常");
              return;
            }
            if(ids[1] != that.curRow.partId) {
              that.$toast.fail("请扫申请的备件二维码");
              return;
              return;
            }
            sparePartDetail({
              partId: ids[1],
            }, data => {
              let inData = that.scanIn.data.find(inData => inData.partId == data.id);
              let msg = "扫码成功,请继续";
              if(!inData) {
                that.scanIn.data.push({
                  partId: data.id,
                  refIds: that.curRow.id,
                  name: data.name,
                  standard: data.standard,
                  area: "二级临仓",
                  num: 1
                });
              } else {
                msg = "已扫码过,请继续";
              }
              that.$toast.success({
                message: msg,
              });
            });
          } else {
            that.$toast.fail("不支持的二维码")
          }
        }
      });
    },

    /* 移除扫码项 */
    delDetailFn(inData, index) {
      const that = this;
      that.scanIn.data.splice(index, 1);
    },

    /* 确认扫码入库 */
    confirmScanInFn() {
      const that = this;
      if(that.scanIn.data.length == 0) {
        that.$toast.fail("请先扫码....");
        return;
      }
      procureIn(that.scanIn.data, res => {
        that.$toast.success({
          message: "入库成功",
          onClose: () => {
            that.scanIn.show = false;
            that.scanIn.data.splice(0, that.scanIn.data.length);
          }
        });
      });
    },

    /* 筛选数据 */
    filterDataFn(inData, timer) {
      const that = this;
      that.scanIn.curData = inData;
      clearTimeout(that.queryTimer);
      that.queryTimer = setTimeout(() => {
        that.$refs.sparePartApplyForRef.focus();
        that.actionSheetData.splice(0, that.actionSheetData.length);
        filterSpareArea({
          keyLike: inData.area
        }, data => {
          data.forEach(item => {
            that.actionSheetData.push({
              name: item,
            });
          });
        });
        that.showActionSheet = true;
      }, timer? timer : 2000);
    },

    /* 选择数据 */
    selectFilterDataFn(action) {
      const that = this;
      that.scanIn.curData.area = action.name;
    },
  }
}
</script>

<style lang="scss" scoped>
.spare-part-apply-for {
  height: 100%;
  ::v-deep .van-search {
    z-index: 1;
  }

  .body-scroll {
    height: 79vh;
    .data-card {
      width: 96vw;
      padding: 0 0.8rem;
      margin-left: 2vw;
      background-color: white;
      margin-top: 0.5rem;
      box-shadow: 0.3rem 0.5rem 0.3rem #888888;
      display: flex;
      div {
        display: flex;
        padding: 0.3rem 0rem;
        span {
          line-height: 1rem;
        }
      }
    }

    .status-to-check {
      box-shadow: 0.3rem 0.5rem 0.3rem #c94949;
    }
    .status-to-procure {
      box-shadow: 0.3rem 0.5rem 0.3rem #e78828;
    }
    .status-reject {
      box-shadow: 0.3rem 0.5rem 0.3rem #868686;
    }
    .status-in {
      box-shadow: 0.3rem 0.5rem 0.3rem #41d249;
    }
  }
}
</style>